<template>
  <div class="component">
    <div class="preview-header">
      <h2>预览面板</h2>
      <button 
        @click="handleExportAll" 
        class="btn-export"
        :disabled="!canExport"
        title="一键导出所有格式"
      >
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M8 2V10M8 10L5 7M8 10L11 7" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M2 12V13C2 13.5523 2.44772 14 3 14H13C13.5523 14 14 13.5523 14 13V12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
        </svg>
        一键导出
      </button>
    </div>
    
    <div class="tab-buttons">
      <button 
        @click="activeTab = 'yaml'" 
        :class="['tab-button', activeTab === 'yaml' ? 'active' : '']"
      >
        YAML 预览
      </button>
      <button 
        @click="activeTab = 'xml'" 
        :class="['tab-button', activeTab === 'xml' ? 'active' : '']"
      >
        XML 预览
      </button>
      <button 
        @click="activeTab = 'proto'" 
        :class="['tab-button', activeTab === 'proto' ? 'active' : '']"
      >
        Protobuf 预览
      </button>
    </div>
    
    <div class="preview-content">
      <pre v-if="activeTab === 'yaml'"><code class="language-yaml">{{ yamlContent }}</code></pre>
      <pre v-if="activeTab === 'xml'"><code class="language-xml">{{ xmlContent }}</code></pre>
      <pre v-if="activeTab === 'proto'"><code class="language-protobuf">{{ protoContent }}</code></pre>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick, computed } from 'vue';
import Prism from 'prismjs';
import JSZip from 'jszip';
import 'prismjs/components/prism-yaml.min';
import 'prismjs/components/prism-protobuf.min';
// 使用 prism-markup 代替 prism-xml（markup 包含 XML/HTML 高亮）
import 'prismjs/components/prism-markup.min';
// Protobuf 支持可能随 Prism 版本而异；尽量导入，如果不存在可以移除或降级为 plain text

type TabType = 'yaml' | 'xml' | 'proto';

const props = defineProps<{
  yamlContent?: string;
  xmlContent?: string;
  protoContent?: string;
  templateName?: string;
}>();

const activeTab = ref<TabType>('yaml');

// 检查内容是否有效（不是占位符）
const isValidContent = (content: string | undefined, placeholder: string): boolean => {
  if (!content || content.trim() === '') return false;
  return !content.trim().startsWith(placeholder);
};

// 计算是否可以导出
const canExport = computed(() => {
  return isValidContent(props.yamlContent, '#') || 
         isValidContent(props.xmlContent, '<!--') || 
         isValidContent(props.protoContent, '//');
});

// 检查是否支持 File System Access API
const supportsFileSystemAccess = (): boolean => {
  return 'showDirectoryPicker' in window;
};

// 使用 File System Access API 导出到选择的目录
const exportToDirectory = async (filesToExport: Array<{ content: string; filename: string }>) => {
  try {
    // 让用户选择目录
    const directoryHandle = await window.showDirectoryPicker({
      mode: 'readwrite'
    });

    // 在选择的目录中创建文件
    for (const file of filesToExport) {
      const fileHandle = await directoryHandle.getFileHandle(file.filename, { create: true });
      const writable = await fileHandle.createWritable();
      await writable.write(file.content);
      await writable.close();
    }

    alert(`导出完成！已成功导出 ${filesToExport.length} 个文件到选择的目录。`);
  } catch (error: any) {
    // 用户取消选择目录
    if (error.name === 'AbortError') {
      return;
    }
    console.error('导出失败:', error);
    alert('导出失败，请重试。如果问题持续，请使用 ZIP 打包方式。');
  }
};

// 打包成 ZIP 文件下载
const exportAsZip = async (filesToExport: Array<{ content: string; filename: string }>) => {
  try {
    const zip = new JSZip();

    // 将所有文件添加到 ZIP
    filesToExport.forEach(file => {
      zip.file(file.filename, file.content);
    });

    // 生成 ZIP 文件
    const zipBlob = await zip.generateAsync({ type: 'blob' });
    
    // 下载 ZIP 文件
    const baseName = props.templateName || 'template';
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
    const zipFileName = `${baseName}_${timestamp}.zip`;
    
    const url = URL.createObjectURL(zipBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = zipFileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    alert(`导出完成！已打包为 ZIP 文件：${zipFileName}`);
  } catch (error) {
    console.error('ZIP 打包失败:', error);
    alert('导出失败，请重试。');
  }
};

// 一键导出所有格式
const handleExportAll = async () => {
  if (!canExport.value) {
    alert('没有可导出的内容');
    return;
  }

  const baseName = props.templateName || 'template';
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
  const fileName = `${baseName}_${timestamp}`;

  const filesToExport: Array<{ content: string; filename: string }> = [];

  // 收集要导出的文件
  if (isValidContent(props.yamlContent, '#')) {
    filesToExport.push({
      content: props.yamlContent!,
      filename: `${fileName}.yaml`
    });
  }

  if (isValidContent(props.xmlContent, '<!--')) {
    filesToExport.push({
      content: props.xmlContent!,
      filename: `${fileName}.xml`
    });
  }

  if (isValidContent(props.protoContent, '//')) {
    filesToExport.push({
      content: props.protoContent!,
      filename: `${fileName}.proto`
    });
  }

  if (filesToExport.length === 0) {
    alert('没有可导出的内容');
    return;
  }

  // 如果支持 File System Access API，让用户选择目录
  if (supportsFileSystemAccess()) {
    await exportToDirectory(filesToExport);
  } else {
    // 否则打包成 ZIP 文件下载
    await exportAsZip(filesToExport);
  }
};

// 监听内容变化，重新高亮
watch([() => props.yamlContent, () => props.xmlContent, () => props.protoContent], () => {
  highlightCode();
});

// 切换标签时重新高亮
watch(activeTab, () => {
  highlightCode();
});

// 初始加载时高亮
onMounted(() => {
  highlightCode();
});

// 代码高亮
const highlightCode = () => {
  // 使用 nextTick 确保 DOM 更新完成后再高亮
  nextTick(() => {
    Prism.highlightAll();
  });
};
</script>

<style scoped>
.preview-content {
  margin-top: 1rem;
  width: 100%;
  overflow-x: auto;
}

.preview-content pre {
  margin: 0;
  border-radius: var(--radius-md);
  overflow-x: auto;
  overflow-y: auto;
  width: 100%;
  min-width: 0;
  white-space: pre;
  word-wrap: normal;
}

.preview-content pre code {
  display: block;
  overflow-x: visible;
  white-space: pre;
  word-wrap: normal;
}

.preview-content pre:empty::before {
  content: '暂无内容';
  color: var(--text-secondary);
  font-style: italic;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.btn-export {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 16px;
  background: linear-gradient(135deg, var(--success-color) 0%, #059669 100%);
  color: white;
  border: none;
  border-radius: var(--radius-sm);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.btn-export:hover:not(:disabled) {
  background: linear-gradient(135deg, var(--success-hover) 0%, #047857 100%);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.btn-export:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: var(--shadow-sm);
}

.btn-export:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: var(--secondary-color);
}

.btn-export svg {
  flex-shrink: 0;
}
</style>